package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.secretId}")
    private String secretId;


    /**
     * 获取openId
     *
     * @param code 小程序传递的code值
     * @return openId
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secretId);
        paramMap.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        String openid = jsonObject.getStr("openid");

        return openid;
    }

    /**
     * 获取手机号
     *
     * @param detailcode
     * @return phoneCode
     */
    @Override
    public String getPhoneNumber(String detailcode) {
        String accessToken = getAccessToken();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", detailcode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.getInt("errcode").equals(0)){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        String phoneNumber = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        return phoneNumber;
    }

    /**
     * 获取accessToken
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secretId);
        String result = HttpUtil.get(TOKEN_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        String accessToken = jsonObject.getStr("access_token");
        return accessToken;
    }


}
